/**
 * @filename:SysMenuServiceImpl 2025-05-09
 * @project starhub-schema  V1.0
 */
package com.starhub.engine.sys.menu.service.impl;

import com.starhub.common.bean.BrowserBean;
import com.starhub.common.sys.user.LoginUser;
import com.starhub.engine.generator.genid.IdGenerator;
import com.starhub.engine.sys.menu.entity.SysMenu;
import com.starhub.engine.sys.menu.dao.SysMenuDao;
import com.starhub.engine.sys.menu.service.SysMenuService;
import com.starhub.utils.ColorUtil;
import com.starhub.utils.Util;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.*;
import java.util.stream.Collectors;

/**   
 * @Description:(菜单设置服务实现)
 *
 * @version: V1.0
 * @author: luosw
 * 
 */
@Service
public class SysMenuServiceImpl implements SysMenuService {
    @Autowired
    private SysMenuDao menuDao;

    /**
    * 新增
    * @param user
    * @param menu
    * @return
    */
    public Long add(LoginUser user, SysMenu menu){

        Long id = IdGenerator.generateId();
        menu.setStatus(menu.getStatus().equals("true") ? "active" : "inactive");
        //数据封装，默认值添加
        menu.setId(id);
        menu.setCreateTime(new Date());
        menu.setUpdateTime(new Date());
        menu.setDeleteType(0);

        menuDao.insertSelective(menu);
        return id;
    }

    /**
    * 更新
    * @param user
    * @param menu
    * @return
    */
    public SysMenu update(LoginUser user, SysMenu menu){
        menu.setUpdateTime(new Date());
        menu.setStatus(menu.getStatus().equals("true") ? "active" : "inactive");
        //不允许更新的属性设置为null
        menuDao.updateByPrimaryKeySelective(menu);
        return menu;
    }

    /**
    * 基本信息获取
    * @param user
    * @param id
    * @return
    */
    public SysMenu getInfo(LoginUser user, Long id){

        SysMenu menu = menuDao.selectByPrimaryKey(id);
        return menu;
    }

    /**
    * (批量)删除，同时支持单条或者批量,此方法为逻辑删除
    * @param user
    * @param ids
    */
    public void deleteByType(LoginUser user, String ids,int deleteType){

        //数组转换
        List<Long> idList = Arrays.stream(ids.split(","))
            .map((id) -> Long.parseLong(id))
            .collect(Collectors.toList());
            //删除状态，目前只有1的逻辑
        menuDao.deleteSysMenuByType(idList, deleteType);
    }

    /**
    * 根据id删除，此方法为真实删除
    * @param user
    * @param ids
    */
    public void deleteRecord(LoginUser user, String ids){

        //数组转换
        List<Long> idList = Arrays.stream(ids.split(","))
            .map((id) -> Long.parseLong(id))
            .collect(Collectors.toList());
        menuDao.deleteSysMenuRecord(idList);
    }

    /**
    * 列表查询
    * @param user
    * @param params
    */
    public List<SysMenu> getList(LoginUser user,  Map<String , Object>  params){

        List<SysMenu> menuList =  new ArrayList<SysMenu>();
            //TODO
        int pageSize = 10;
        int current = 1;
        SysMenu record = new SysMenu();
        record.setDeleteType(0);
        menuList = menuDao.selectByPrimaryKeySelective(record);
        return menuList;
    }

    @Override
    public Map<String, BrowserBean> getActiveMenu(LoginUser user, Map<String, Object> params) {

        Map<String, BrowserBean> result = new HashMap<>();
        SysMenu record = new SysMenu();
        record.setDeleteType(0);
        List<SysMenu> menuList = menuDao.selectByPrimaryKeySelective(record);
        // 查询所有菜单
        List<String> dColors = ColorUtil.dColors;
        int i =0 ;
        if(CollectionUtils.isNotEmpty(menuList)){
            for(SysMenu sysMenu : menuList){
                int co = i % dColors.size();
                i++;
                String color = dColors.get(co);
                BrowserBean bean = new BrowserBean(Util.null2String(sysMenu.getId()) ,sysMenu.getMenuName(),color);
                result.put(Util.null2String(sysMenu.getId()),bean);
            }
        }
        return result;
    }


    @Override
    public List<BrowserBean> getActiveMenuTree(LoginUser user, Map<String, Object> params) {

        List<BrowserBean> menuTrees = new ArrayList<>();
        SysMenu record = new SysMenu();
        record.setDeleteType(0);
        List<SysMenu> menuList = menuDao.selectByPrimaryKeySelective(record);
        // 查询所有菜单
        return convertToTree(menuList);
    }


    public static List<BrowserBean> convertToTree(List<SysMenu> menuList) {
        // 创建ID到BrowserBean的映射
        Map<Long, BrowserBean> beanMap = new HashMap<>();
        // 创建根节点列表
        List<BrowserBean> rootNodes = new ArrayList<>();
        // 第一步：创建所有节点的BrowserBean
        for (SysMenu menu : menuList) {
            BrowserBean bean = new BrowserBean();
            bean.setValue(String.valueOf(menu.getId()));
            bean.setTitle(menu.getMenuName());
            // 可以设置颜色，这里使用默认值
            bean.setChildren(new ArrayList<>());
            beanMap.put(menu.getId(), bean);
        }

        // 第二步：构建树形结构
        for (SysMenu menu : menuList) {
            BrowserBean currentBean = beanMap.get(menu.getId());
            Long parentId = menu.getParentId();
            if (parentId == null || parentId == 0) {
                // 根节点
                rootNodes.add(currentBean);
            } else {
                // 找到父节点
                BrowserBean parentBean = beanMap.get(parentId);
                if (parentBean != null) {
                    parentBean.getChildren().add(currentBean);
                }
            }
        }
        return rootNodes;
    }
}